import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import * as monaco from 'monaco-editor'
import type { EditorConfig } from '@/types'

export function useEditor(config: Partial<EditorConfig> = {}) {
  const editorRef = ref<monaco.editor.IStandaloneCodeEditor | null>(null)
  const containerRef = ref<HTMLElement | null>(null)
  const isReady = ref(false)
  const isInitialized = ref(false)

  // 默认配置
  const defaultConfig: EditorConfig = {
    language: 'json',
    theme: 'vs-dark', // 将在初始化后动态更新
    fontSize: 14,
    wordWrap: true,
    minimap: false,
    lineNumbers: true,
    readOnly: false,
    ...config,
  }

  // 获取当前主题
  function getCurrentTheme(): string {
    return document.documentElement.classList.contains('dark') ? 'vs-dark' : 'vs'
  }

  // 初始化编辑器
  async function initEditor() {
    if (!containerRef.value || isInitialized.value) {
      return
    }

    await nextTick()

    try {
      // 确保Monaco环境已准备好
      if (!monaco.editor) {
        console.warn('Monaco editor not ready, retrying...')
        setTimeout(initEditor, 100)
        return
      }

      // 获取当前主题
      const currentTheme = getCurrentTheme()

      // 创建编辑器实例，优化性能配置
      editorRef.value = monaco.editor.create(containerRef.value, {
        value: '',
        language: defaultConfig.language,
        theme: currentTheme,
        fontSize: defaultConfig.fontSize,
        wordWrap: defaultConfig.wordWrap ? 'on' : 'off',
        minimap: { enabled: defaultConfig.minimap },
        lineNumbers: defaultConfig.lineNumbers ? 'on' : 'off',
        readOnly: defaultConfig.readOnly,
        automaticLayout: true,
        scrollBeyondLastLine: false,
        renderWhitespace: 'selection',
        tabSize: 2,
        insertSpaces: true,
        formatOnPaste: true,
        formatOnType: true,
        // 性能优化配置
        folding: true,
        foldingStrategy: 'indentation',
        showFoldingControls: 'mouseover',
        smoothScrolling: true,
        cursorSmoothCaretAnimation: 'on',
        renderLineHighlight: 'gutter',
        occurrencesHighlight: 'singleFile',
        codeLens: false,
        // 减少不必要的功能以提升性能
        glyphMargin: false,
      })

      isInitialized.value = true
      isReady.value = true

      // 确保主题正确应用
      setTimeout(() => {
        if (editorRef.value) {
          const theme = getCurrentTheme()
          monaco.editor.setTheme(theme)
        }
      }, 50)
    } catch (error) {
      console.error('Failed to initialize Monaco editor:', error)
      // 重试初始化
      setTimeout(initEditor, 200)
    }
  }

  // 设置编辑器内容
  function setValue(value: string) {
    if (editorRef.value) {
      editorRef.value.setValue(value)
    }
  }

  // 获取编辑器内容
  function getValue(): string {
    return editorRef.value?.getValue() || ''
  }

  // 设置语言模式
  function setLanguage(language: string) {
    if (editorRef.value) {
      const model = editorRef.value.getModel()
      if (model) {
        monaco.editor.setModelLanguage(model, language)
      }
    }
  }

  // 设置主题，添加防抖和错误处理
  function setTheme(theme: string) {
    if (editorRef.value && monaco.editor) {
      try {
        monaco.editor.setTheme(theme)
      } catch (error) {
        console.warn('Failed to set Monaco theme:', error)
      }
    }
  }

  // 根据系统主题自动设置Monaco主题，优化性能
  let themeUpdateTimeout: number
  function updateMonacoTheme() {
    // 防抖主题更新，避免频繁切换
    clearTimeout(themeUpdateTimeout)
    themeUpdateTimeout = setTimeout(() => {
      const isDarkMode = document.documentElement.classList.contains('dark')
      const theme = isDarkMode ? 'vs-dark' : 'vs'
      setTheme(theme)
    }, 100)
  }

  // 格式化代码
  async function formatCode() {
    if (editorRef.value) {
      try {
        await editorRef.value.getAction('editor.action.formatDocument')?.run()
      } catch (error) {
        console.warn('格式化失败:', error)
      }
    }
  }

  // 聚焦编辑器
  function focus() {
    if (editorRef.value) {
      editorRef.value.focus()
    }
  }

  // 设置只读状态
  function setReadOnly(readOnly: boolean) {
    if (editorRef.value) {
      editorRef.value.updateOptions({ readOnly })
    }
  }

  // 监听内容变化
  function onContentChange(callback: (value: string) => void) {
    if (editorRef.value) {
      const model = editorRef.value.getModel()
      if (model) {
        return model.onDidChangeContent(() => {
          callback(getValue())
        })
      }
    }
    return null
  }

  // 销毁编辑器
  function dispose() {
    if (editorRef.value) {
      editorRef.value.dispose()
      editorRef.value = null
      isReady.value = false
    }
  }

  // 获取编辑器实例
  function getEditor() {
    return editorRef.value
  }

  // 生命周期
  onMounted(() => {
    // 延迟初始化，确保DOM完全准备好
    setTimeout(() => {
      initEditor()
    }, 50)

    // 监听主题变化，优化性能
    const observer = new MutationObserver((mutations) => {
      // 只在class属性变化时更新主题
      const hasClassChange = mutations.some(
        (mutation) => mutation.type === 'attributes' && mutation.attributeName === 'class',
      )
      if (hasClassChange) {
        updateMonacoTheme()
      }
    })

    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['class'],
    })

    // 初始化主题
    setTimeout(() => {
      updateMonacoTheme()
    }, 100)

    // 清理观察器
    onUnmounted(() => {
      observer.disconnect()
      if (themeUpdateTimeout) {
        clearTimeout(themeUpdateTimeout)
      }
    })
  })

  onUnmounted(() => {
    dispose()
  })

  return {
    // refs
    containerRef,
    editorRef,
    isReady,

    // methods
    initEditor,
    setValue,
    getValue,
    setLanguage,
    setTheme,
    formatCode,
    focus,
    setReadOnly,
    onContentChange,
    dispose,
    getEditor,
    updateMonacoTheme,
  }
}

// 创建JSON编辑器的便捷函数
export function useJsonEditor(config: Partial<EditorConfig> = {}) {
  return useEditor({
    language: 'json',
    ...config,
  })
}

// 创建TOML编辑器的便捷函数
export function useTomlEditor(config: Partial<EditorConfig> = {}) {
  return useEditor({
    language: 'plaintext', // Monaco没有内置TOML支持
    readOnly: true,
    ...config,
  })
}
